package thread;
class Counter {
    private int count = 0;
    public void add(){
        //synchronized (this) {
            count++;
        //}
    }
    //synchronized public void add(){与上面等价。一进方法就加锁
    //    count++;
    //}
    public int get(){
        return count;
    }
}
public class Demo20 {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        //Object locker = new Object();

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                synchronized (counter) {//加锁具体是针对哪个对象不重要。。。重要的是两个线程是否是针对同一个对象来加锁
                    counter.add();;
                }
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                synchronized (counter) {
                    counter.add();;
                }
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("count = "+ counter.get());
    }
}
